<template>
  <div id="staModuleMenuDiv">
    <vxe-toolbar perfect>
      <template #buttons>
        <div class="smallToolTitle">用户对照</div>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :disabled="disabledTag" :loading="qloading" @click="findUserList"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加" :disabled="disabledTag" @click="addUserDialog()"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="userDelete"></vxe-button>
      </template>
    </vxe-toolbar>
    <div class="tableBox">
      <vxe-table ref="sysUserTableRef" :data="sysUserList" :loading="qloading" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true}" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
        <vxe-column type="checkbox" width="30" align="center"></vxe-column>
        <vxe-column type="seq" title="#" width="30"></vxe-column>
        <vxe-column field="username" title="用户编号" width="60"></vxe-column>
        <vxe-column field="realname" title="用户名称" min-width="160px" ></vxe-column>
      </vxe-table>
    </div>
    <el-dialog title="用户" :show-close="false" v-model="showMenuDialog" append-to-body width="1000px" :close-on-click-modal="false" destroy-on-close v-if="showMenuDialog">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-input style="width: 130px" v-model="searchMenuForm.seachValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findUserDataList" @keyup="keyupMenuEnter" @search-click="findUserDataList()"></vxe-input>
          <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="findUserDataList"></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="tableBody" style="height: 600px">
        <vxe-table ref="userDataTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="userDataList" :loading="lloading" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" :checkbox-config="{
                  checkMethod: checCheckboxkMethod2,
                  visibleMethod: showCheckboxkMethod2,
                  checkRowKeys: defaultSelecteRowKeys
                }" resizable show-overflow keep-source>

          <vxe-column type="checkbox" width="30"></vxe-column>
          <vxe-column type="seq" title="序号" width="80"></vxe-column>
          <vxe-column field="username" title="用户编号" width="80"></vxe-column>
          <vxe-column field="realname" title="用户名称" min-width="140"></vxe-column>
        </vxe-table>
        <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total'
              ]" @page-change="handleSizeChange($event)"></vxe-pager>
        <div class="dialog-footer flex right justify-end">
          <el-button type="primary" @click="saveBacthMenu('userDataTableRef')">确定</el-button>
          <el-button @click="closeMenuDialog('userDataTableRef')">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
defineExpose({ initPage });

let disabledTag = ref(true); //中间质控品维护按钮标记
let qloading = ref(false); //右侧质控表格加载+刷新
let sysUserList: any = reactive([]);
let sysUserInfo = ref(null);
let showMenuDialog = ref(false);
let lloading = ref(false); //弹框表格数据加载状态

let dictTreeTypeCodes: any = reactive(['JYGZZ', 'YQDL', 'LABITEMKIND']);

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});
let searchMenuForm = reactive({
  seachValue: ''
});

function initPage(row: any) {
  if (isEmpty(row)) {
    sysUserInfo.value = {};
  } else {
    sysUserInfo.value = row;
    findUserList();
  }
  if (!sysUserInfo.value.id) {
    disabledTag.value = true;
  } else {
    disabledTag.value = false;
  }
}


function findUserList() {
  if (isEmpty(sysUserInfo.value)) {
    VxeMessage('请选模型', VxeNotifyType.error);
  } else {
    qloading.value = true;
    sysUserList.length = 0; //放入数据前清空数据
    const url = '/lis/cri/post/findUserCompareByPost';
    proxy.$http
        //注意此处的数据条数
        .get(url, {
          params: { postNo: sysUserInfo.value.postNo }
        })
        .then((res: any) => {
          sysUserList.push(...res.data);
          qloading.value = false;
        })
        .catch((err: any) => {
          qloading.value = false;
          VxeMessage('获取右侧报告项目失败', VxeNotifyType.error);
        });
  }``
}

// 添加按钮
function addUserDialog() {
  if (isEmpty(sysUserInfo.value)) {
    VxeMessage('请选择用户', VxeNotifyType.error);
  } else {
    findUserDataList();
    showMenuDialog.value = true;
  }
}
let userDataList: any = reactive([]);

function findUserDataList() {
  lloading.value = true;
  userDataList.length = 0; //放入数据前清空数据
  const url = '/api/user/getUserPageList';
  proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: {
          keywords: searchMenuForm.seachValue,
          pageIndex: page.currentPage,
          pageSize: page.pageSize
        }
      })
      .then((res: any) => {
        userDataList.push(...res.data.records);
        page.totalResult = res.data.total;
        const itemDictIds = sysUserList.map((m) => m.username);
        const ilist = userDataList.filter((p: any) => itemDictIds.includes(p.username));
        const $table = proxy.$refs.userDataTableRef;
        $table.setCheckboxRow(ilist, true);
        lloading.value = false;
      })
      .catch((err: any) => {
        lloading.value = false;
        VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
      });
}

// 回车查询
function keyupMenuEnter(e: any) {
  if (e.$event.code == 'Enter') {
    page.currentPage = 1;
    findUserDataList();
  }
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findUserDataList();
}

function saveBacthMenu() {
  const selectRows = (proxy.$refs.userDataTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    const addUserDataList = [];
    for (const sltRow of selectRows) {
      const moduleMenu = sysUserList.find((qc: any) => qc.username == sltRow.username);
      if (isEmpty(moduleMenu)) {
        const addModuleMenu = {
          postNo: sysUserInfo.value.postNo,
          userNo: sltRow.username,
          userNa: sltRow.realname
        };
        addUserDataList.push(addModuleMenu);
      }
    }
    if (addUserDataList.length > 0) {
      const url = '/lis/cri/post/saveBatchPostUser';
      proxy.$http
          .post(url, addUserDataList)
          .then((res: any) => {
            findUserList(); // 获取检验仪器表格数据
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
    } else {
      VxeMessage('请选择要添加的数据', VxeNotifyType.error);
    }
  } else {
    VxeMessage('请选择要添加的数据', VxeNotifyType.error);
  }
  closeMenuDialog();
}

function userDelete() {
  const sltModuleMenus = (proxy.$refs.sysUserTableRef as any).getCheckboxRecords();
  if (!(sltModuleMenus.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
        .$confirm('确定要删除当前勾选的数据？', '提示', {
          cancelButtonClass: 'cancel-button',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          const data={
            postNo: sysUserInfo.value.postNo,
            userNoList: sltModuleMenus.map((m: any) => m.username)
          }
          const url = '/lis/cri/post/batchDeletePostUserList';
          proxy.$http
              .post(url, data)
              .then((res: any) => {
                findUserList(); // 获取检验仪器表格数据
                VxeMessage(res.status.msg, VxeNotifyType.success);
              })
              .catch((err: any) => {
                VxeMessage(err, VxeNotifyType.error);
              });
        })
        .catch((err: any) => {
          // VxeMessage(err, VxeNotifyType.error);
        });
  }
}

// 弹框取消按钮
function closeMenuDialog() {
  searchMenuForm.seachValue = '';
  showMenuDialog.value = false;
}

let defaultSelecteRowKeys = reactive([]);
// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  defaultSelecteRowKeys.length = 0;
  const obj = sysUserList.filter((p: any) => {
    defaultSelecteRowKeys.push(p.username);
    return p.username == row.username;
  });
  return obj.length == 0;
}

// 弹框 表格复选框 设置(是否显示复选框)
function showCheckboxkMethod2({ row }: any) {
  const obj = sysUserList.filter((p: any) => {});
  return obj.length == 0;
}
</script>

<style lang="scss" scoped>
#staModuleMenuDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }
}
</style>